
import {isValidKey} from '../type/utils'

export default class socketService {
    static instance: any = null
    static get Instance () {
      if (!this.instance) {
        this.instance = new socketService()
      }
      return this.instance
    }
    ws: any = null
    callBackMapping: { [key: string]: any } = {}
    connected = false
    sendtime = 0
    contimr = 0
    con () {
        if (!window.WebSocket) {
            return alert('您的浏览器不支持WebSocket')
        }
        this.ws = new WebSocket('ws://localhost:9998')
        this.ws.onopen = () => {
            console.log('连接成功...');
            this.connected = true
            this.contimr = 0
        }
        this.ws.onclose = () => {
            console.log('连接失败...');
            this.contimr++
            this.connected = false
            setTimeout(() => {
                this.con()
            }, this.contimr * 500);
        }
        this.ws.onmessage = (msg: any) => {
            console.log('接受服务器发送数据：');
            const resv = JSON.parse(msg.data)
            const socketType = resv.socketType
            // console.log(this.callBackMapping);
            if (this.callBackMapping[socketType]) {
                const action = resv.action  
                if (action === 'getData') {
                    const realData = JSON.parse(resv.data)
                    this.callBackMapping[socketType].call(this, realData)
                } else if (action === 'fullScreen') {
                    this.callBackMapping[socketType].call(this, resv)
                } else if (action === 'themeChange') {
                    this.callBackMapping[socketType].call(this, resv)
                }
            }
        }
    }
    registerCallBack (socketType: string, callback: any) {
        this.callBackMapping[socketType] = callback
    }
    unRegisterCallBack (socketType: string) {
        this.callBackMapping[socketType] = null
    }
    send (data: any) {
        if (this.connected) {
            this.sendtime = 0
            this.ws.send(JSON.stringify(data))
        } else {
            this.sendtime++
            setTimeout(() => {
                this.send(data)
            }, 500 * this.sendtime)
        }
    }
}